package geektime.concurrent.part3;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 演示在流中使用CompletableFuture.supplyAsync和CompletableFuture.thenApply
 */
public class SupplyAsyncStreamDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(2021, 2022, 2100);
        List<String> stringList = numbers.stream()
            .map(data -> CompletableFuture.supplyAsync(() -> getDataById(data)))
            .map(cf -> cf.thenApply(data -> sendData(data)))
            .map(CompletableFuture::join)
            .collect(Collectors.toList());
        System.out.println(stringList);
    }

    private static String getDataById(Integer id) {
        System.out.println("getDataById is executed by: " + Thread.currentThread().getName());
        return "data:" + id;
    }

    private static String sendData(String data) {
        System.out.println("sendData is executed by: " + Thread.currentThread().getName());
        System.out.println(data);
        return data;
    }
}
